//
//  MyInfoViewController.m
//  KeepFit
//
//  Created by Fuzzie Liu on 15/10/28.
//  Copyright © 2015年 Fuzzie Liu. All rights reserved.
//

#import "MyInfoViewController.h"
#import "AboutMeViewController.h"//关于我们界面
#import "RelationViewController.h"//联系我们界面
#import "FeedbackViewController.h"//反馈界面
#import "collectionViewController.h"//收藏界面
@interface MyInfoViewController () <UITableViewDataSource, UITableViewDelegate>
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) UIImageView *backgroundImageView;
@property (strong, nonatomic) UIImageView *headImageView;
@property (strong, nonatomic) UILabel *informationLabel;
@property (nonatomic, assign) BOOL isNeight;//是否是夜间模式

@end

@implementation MyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isNeight = NO;
    
    UIImage *image = [UIImage imageNamed:@"wodea@2x.png"];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *hlImage = [UIImage imageNamed:@"wode@2x.png"];
    hlImage = [hlImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBarItem.image = image;
    self.tabBarItem.selectedImage = hlImage;
    
    // 初始化healthStore变数
    healthStore = [HKHealthStore new];

    // 确认设备是否支持Headth Store
    if ([HKHealthStore isHealthDataAvailable]) {
        // 设置哪些数据要写入HealthKit
        NSSet *writeDataTypes = [self dataTypesToWrite];
        // 设置要从Health Store读出哪些数据
        NSSet *readDataTypes = [self dataTypesToRead];
        // 向Health Store请求访问数据的共享权限
        [healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {
            if (error) {
                NSLog(@"请求数据共享失败: %@", error);
            } else {
                // 请求成功
                // 取得main queue的目的是为了将读取到的数据显示在视图组件上
                // 但这里我们用NSLog将数据显示在debug console，理论上程序代码不需要放在
                // main queue中，这样写主要是怕读者忘记要先取得main queue
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 调用自定义method，取得生日、性别与血型
//                    [self readDataOfMe];
                });
            }
        }];
    }

    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height / 3, self.view.bounds.size.width, self.view.bounds.size.height / 3 * 2) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//设置没有分割线
    self.tableView.scrollEnabled = NO;//设置 tableView 不可以滑动
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.backgroundImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"07873faab430d22054a0a76e934ebd48.jpg"]];
    self.backgroundImageView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height / 3);
    [self.view addSubview:self.backgroundImageView];
    
    self.headImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"09691fd8076f69fc8f80f3d186101077.gif"]];
    self.headImageView.frame = CGRectMake(self.backgroundImageView.bounds.size.width / 2 - 50, self.backgroundImageView.bounds.size.height / 2 - 50, 100, 100);
    self.headImageView.layer.cornerRadius = self.headImageView.frame.size.width / 2;
    self.headImageView.clipsToBounds = YES;
    [self.backgroundImageView addSubview:self.headImageView];
    
    //加统计图类型
    self.informationLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, self.backgroundImageView.bounds.size.height - 40, self.backgroundImageView.bounds.size.width - 60, 30)];
    self.informationLabel.backgroundColor = [UIColor clearColor];
    self.informationLabel.textAlignment = NSTextAlignmentCenter;
    self.informationLabel.text = [self readDataOfMe];
    [self.backgroundImageView addSubview:self.informationLabel];

    
}

//设置 tableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        cell.contentView.backgroundColor = [UIColor whiteColor];
    }
    if (indexPath.row == 0) {
        NSString * path = [self getCachesPath];
        NSLog(@"缓存路径:%@",path);
        CGFloat stringSize = [self folderSizeAtPath:path];
        CGFloat imageSize = [[SDImageCache sharedImageCache] getSize]/1024/1024;
        cell.textLabel.text = [NSString stringWithFormat:@"清理缓存  当前缓存%.2fM",imageSize + stringSize];
        cell.imageView.image = [UIImage imageNamed:@"iconfont-qingchuhuancun"];
        return cell;
    }
    if (indexPath.row == 1) {
        cell.textLabel.text = @"关于 KeepFit";
        cell.imageView.image = [UIImage imageNamed:@"iconfont-guanyu"];
        return cell;
    }
    if (indexPath.row == 2) {
        cell.textLabel.text = @"联系我们";
        cell.imageView.image = [UIImage imageNamed:@"iconfont-ordinarycontact"];
        return cell;
    }
    if (indexPath.row == 3) {
        cell.textLabel.text = @"反馈与意见";
        cell.imageView.image = [UIImage imageNamed:@"iconfont-fankui"];
        return cell;
    }
    if (indexPath.row == 4) {
        cell.textLabel.text = @"我的收藏";
        cell.imageView.image = [UIImage imageNamed:@"iconfont-shoucang"];
        return cell;
    }
    if (indexPath.row == 5) {
        if (self.isNeight == NO) {
            cell.textLabel.text = @"夜间护眼";
            cell.imageView.image = [UIImage imageNamed:@"iconfont-yueliang"];
            return cell;
        }else{
            cell.textLabel.text = @"白天明亮";
            cell.imageView.image = [UIImage imageNamed:@"iconfont-taiyang"];
            return cell;

        }
    }

    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    return cell;
}

//cell的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"确定清除缓存吗?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[SDImageCache sharedImageCache] cleanDisk];
            BOOL result = [self deleteFolderAtPath:[self getCachesPath]];
            if (result) {
                NSLog(@"清除缓存成功");
                
            }else{
                NSLog(@"清除缓存失败");
            }
            [self.tableView reloadData];
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    if (indexPath.row == 1) {
        AboutMeViewController *aboutMeVC = [[AboutMeViewController alloc] init];
        [self.navigationController pushViewController:aboutMeVC animated:YES];
    }
    if (indexPath.row == 2) {
        RelationViewController *relationVC = [[RelationViewController alloc] init];
        [self.navigationController pushViewController:relationVC animated:YES];
    }
    if (indexPath.row == 3) {
        FeedbackViewController *feedbackVC = [[FeedbackViewController alloc] init];
        [self.navigationController pushViewController:feedbackVC animated:YES];
    }
    if (indexPath.row == 4) {
        collectionViewController *collectionVC = [[collectionViewController alloc] init];
        [self.navigationController pushViewController:collectionVC animated:YES];
    }
    if (indexPath.row == 5) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        
        if (self.isNeight == NO) {
            NSLog(@"变成夜间模式吧");
            self.isNeight = !self.isNeight;
            [user setBool:YES forKey:@"Night"];
            [user setInteger:0xffffff forKey:@"DefaultColor"];
            [user setInteger:0x434343 forKey:@"TextColor"];

            [self.tableView reloadData];
        }else{
            NSLog(@"变成白天模式吧");
            self.isNeight = !self.isNeight;
            [user setBool:NO forKey:@"Night"];
            [user setInteger:0x434343 forKey:@"DefaultColor"];
            [user setInteger:0xffffff forKey:@"TextColor"];
            [self.tableView reloadData];
        }
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center postNotificationName:@"NightVersion" object:nil userInfo:nil];
    }

}


//设置 cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.view.bounds.size.height / 10;
}

//设置个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 6;
}

//获取缓存文件路径
-(NSString *)getCachesPath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [NSString stringWithFormat:@"%@/",documentsDirectory];
    return path;
}

- (float) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];//从前向后枚举器／／／／//
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

//计算缓存文件的大小的M
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

//删除文件夹路径
- (BOOL) deleteFolderAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return NO;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];//从前向后枚举器／／／／//
    NSString* fileName;
    BOOL result = NO;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        NSFileManager *manager = [NSFileManager defaultManager];
        result = [manager removeItemAtPath:fileAbsolutePath error:nil];
    }
    return YES;
}

- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;//设置 navigationBar隐藏
}

// 设置要从Health Store读出哪些类型的数据
-(NSSet *)dataTypesToRead {
    return [NSSet setWithObjects:
            //出生日期
            [HKCharacteristicType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth],
            //性别
            [HKCharacteristicType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],
            //血型
            [HKCharacteristicType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBloodType],
            //步行+跑步
            [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
            nil];
}

// 设置哪些类型的数据要写入 Health Store
-(NSSet *)dataTypesToWrite {
    return nil;
}

-(NSString *)readDataOfMe
{
    NSString *str = [NSString string];
    NSError *error;
    // 取得生日数据
    NSDate *dateOfBirth = [healthStore dateOfBirthWithError:&error];
    if (!dateOfBirth) {
        str = @"年龄:未知 | ";
    } else {
        NSInteger birthInteger = [[[NSString stringWithFormat:@"%@",dateOfBirth] substringToIndex:4] integerValue];
        NSInteger nowInteger = [[[NSString stringWithFormat:@"%@",[NSDate date]] substringToIndex:4] integerValue];
        
        str = [NSString stringWithFormat:@"年龄:%ld | ",nowInteger - birthInteger - (long)1];
    }
    
    // 取得性别数据
    HKBiologicalSexObject *sex = [healthStore biologicalSexWithError:&error];
    if (!sex) {
        str = [str stringByAppendingString:@"性别:未知 | "];
    } else {
        switch (sex.biologicalSex) {
            case HKBiologicalSexFemale:
                str = [str stringByAppendingString:@"性别:女 | "];
                break;
                
            case HKBiologicalSexMale:
                str = [str stringByAppendingString:@"性别:男 | "];
                break;
                
            case HKBiologicalSexNotSet:
                str = [str stringByAppendingString:@"性别:未知 | "];
                break;
            default:
                str = [str stringByAppendingString:@"性别:未知 | "];
                break;
        }
    }
    
    // 取得血型数据
    HKBloodTypeObject *blood = [healthStore bloodTypeWithError:&error];
    if (!blood) {
        str = [str stringByAppendingString:@"血型:未知"];
    } else {
        switch (blood.bloodType) {
            case HKBloodTypeABNegative:
                str = [str stringByAppendingString:@"血型:AB-"];
                break;
                
            case HKBloodTypeABPositive:
                str = [str stringByAppendingString:@"血型:AB+"];
                break;
                
            case HKBloodTypeANegative:
                str = [str stringByAppendingString:@"血型:A-"];
                break;
                
            case HKBloodTypeAPositive:
                str = [str stringByAppendingString:@"血型:A+"];
                break;
                
            case HKBloodTypeBNegative:
                str = [str stringByAppendingString:@"血型:B-"];
                break;
                
            case HKBloodTypeBPositive:
                str = [str stringByAppendingString:@"血型:B+"];
                break;
                
            case HKBloodTypeONegative:
                str = [str stringByAppendingString:@"血型:O-"];
                break;
                
            case HKBloodTypeOPositive:
                str = [str stringByAppendingString:@"血型:O+"];
                break;
                
            case HKBloodTypeNotSet:
                str = [str stringByAppendingString:@"血型:未知"];
                break;
        }
    }
    return str;
}


//内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
